package com.nbjtjc.safe.qrCode;

import org.w3c.dom.Element;

import javax.imageio.*;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;

/**
 * JPEG 处理方式
 * Created by qinhailong on 25/06/2017.
 */
public class JpegDPIProcessor implements ImageDPIProcessor {

    private String formatName = "jpeg";

    /**
     * 根据文件后缀扩展名判断是否能进行处理
     *
     * @param fileName
     * @return
     */
    @Override
    public boolean canHandle(String fileName) {
        assert fileName != null : "fileName should not be null";

        return fileName.endsWith("jpg") || fileName.endsWith("jpeg") || fileName.endsWith("JPG")
                || fileName.endsWith("JPEG");
    }

    /**
     * @param srcimage
     * @param dpi
     * @return
     * @throws Exception
     */
    @Override
    public BufferedImage process(BufferedImage srcimage, int dpi) throws Exception {
        for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
            ImageWriter writer = iw.next();

            ImageWriteParam writeParams = writer.getDefaultWriteParam();
            writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            //调整图片质量
            writeParams.setCompressionQuality(1f);

            IIOMetadata data = writer.getDefaultImageMetadata(new ImageTypeSpecifier(srcimage), writeParams);
            Element tree = (Element) data.getAsTree("javax_imageio_jpeg_image_1.0");
            Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
            jfif.setAttribute("Xdensity", dpi + "");
            jfif.setAttribute("Ydensity", dpi + "");
            jfif.setAttribute("resUnits", "1"); // density is dots per inch

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageOutputStream stream = null;
            try {
                stream = ImageIO.createImageOutputStream(out);
                writer.setOutput(stream);
                writer.write(data, new IIOImage(srcimage, null, null), writeParams);
            } finally {
                stream.close();
            }

            ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());    //将b作为输入流；
            return ImageIO.read(in);     //将in作为输入流，读取图片存入image中，而这里in可以为ByteArrayInputStream();
        }
        return null;

    }
}
